// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function () {
    // 初始化所有功能
    initializeApp();
});

// 初始化应用
function initializeApp() {
    // 初始化菜单功能
    initializeMenu();
}

// 检查响应是否为登录页面
function checkLoginPage(responseText) {
    // 检查返回的内容是否包含登录页面的特征
    if (responseText.includes('<title>用户登录</title>') ||
        responseText.includes('login-form') ||
        responseText.includes('用户名') ||
        responseText.includes('密码')) {
        // 如果是登录页面，直接跳转到登录页
        window.location.href = '/login';
        return true;
    }
    return false;
}

// 封装fetch方法，统一处理会话超时
function fetchWithAuth(url, options = {}) {
    // 确保请求包含认证信息
    if (!options.headers) {
        options.headers = {};
    }
    if (!options.headers['X-Requested-With']) {
        options.headers['X-Requested-With'] = 'XMLHttpRequest';
    }

    return fetch(url, options)
        .then(response => {
            // 检查是否重定向到登录页
            if (response.redirected && response.url.includes('/login')) {
                window.location.href = '/login';
                return Promise.reject(new Error('Session expired'));
            }

            // 检查响应状态
            if (!response.ok) {
                return Promise.reject(new Error('Network error: ' + response.status));
            }

            return response.text();
        })
        .then(text => {
            // 检查返回内容是否为登录页面
            if (checkLoginPage(text)) {
                return Promise.reject(new Error('Session expired'));
            }
            // 尝试解析为JSON
            try {
                const jsonData = JSON.parse(text);
                // 检查是否有会话过期的错误码
                if (jsonData.error && jsonData.error === 'SESSION_EXPIRED') {
                    window.location.href = '/login';
                    return Promise.reject(new Error('Session expired'));
                }
                // 检查是否有其他错误码
                if (jsonData.code && jsonData.code !== 0) {
                    return Promise.reject(new Error(jsonData.msg || 'Server error'));
                }
                return jsonData;
            } catch (e) {
                // 如果不是JSON，直接返回文本
                return text;
            }
        })
        .catch(error => {
            // 特别处理会话过期的情况
            if (error.message === 'Session expired') {
                // 已经在checkLoginPage或重定向检查中处理了跳转，这里不需要额外操作
                return Promise.reject(error);
            }
            console.error('Error:', error);
            throw error;
        });
}

// 格式化时间显示
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '';

    try {
        // 解析ISO格式时间字符串
        const date = new Date(dateTimeStr);

        // 转换为东八区时间
        const utcOffset = date.getTimezoneOffset() * 60000; // 转换为毫秒
        const chinaTime = new Date(date.getTime() + utcOffset + 8 * 3600000); // 加上东八区偏移

        // 格式化为 yyyy-MM-dd HH:mm:ss
        const year = chinaTime.getFullYear();
        const month = String(chinaTime.getMonth() + 1).padStart(2, '0');
        const day = String(chinaTime.getDate()).padStart(2, '0');
        const hours = String(chinaTime.getHours()).padStart(2, '0');
        const minutes = String(chinaTime.getMinutes()).padStart(2, '0');
        const seconds = String(chinaTime.getSeconds()).padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    } catch (e) {
        console.error('时间格式化错误:', e);
        return dateTimeStr; // 如果格式化失败，返回原始值
    }
}

// 自定义通知组件
function showNotification(message, type = 'info') {
    // 移除已存在的通知
    const existingNotification = document.getElementById('custom-notification');
    if (existingNotification) {
        existingNotification.remove();
    }

    // 创建通知元素
    const notification = document.createElement('div');
    notification.id = 'custom-notification';
    notification.className = `notification notification-${type}`;

    // 设置通知内容
    notification.innerHTML = `
        <div class="notification-content">
            <span class="notification-message">${message}</span>
            <button class="notification-close">&times;</button>
        </div>
    `;

    // 添加到页面
    document.body.appendChild(notification);

    // 显示动画
    setTimeout(() => {
        notification.classList.add('show');
    }, 10);

    // 绑定关闭事件
    notification.querySelector('.notification-close').addEventListener('click', () => {
        notification.classList.remove('show');
        setTimeout(() => {
            notification.remove();
        }, 300);
    });

    // 3秒后自动关闭
    setTimeout(() => {
        if (document.body.contains(notification)) {
            notification.classList.remove('show');
            setTimeout(() => {
                notification.remove();
            }, 300);
        }
    }, 3000);
}

// 中心模态对话框组件
function showModalDialog(message, title = '提示', type = 'info') {
    return new Promise((resolve) => {
        // 移除已存在的模态框
        const existingModal = document.getElementById('custom-modal-dialog');
        if (existingModal) {
            existingModal.remove();
        }

        // 创建模态框元素
        const modal = document.createElement('div');
        modal.id = 'custom-modal-dialog';
        modal.className = 'custom-modal';

        // 设置模态框内容
        modal.innerHTML = `
            <div class="modal-overlay">
                <div class="modal-container modal-${type}">
                    <div class="modal-header">
                        <h3>${title}</h3>
                    </div>
                    <div class="modal-body">
                        <p>${message}</p>
                    </div>
                    <div class="modal-footer">
                        <button class="modal-confirm-btn">确定</button>
                    </div>
                </div>
            </div>
        `;

        // 添加到页面
        document.body.appendChild(modal);

        // 显示动画
        setTimeout(() => {
            modal.classList.add('show');
        }, 10);

        // 绑定确认按钮事件
        const confirmBtn = modal.querySelector('.modal-confirm-btn');
        const closeModal = () => {
            modal.classList.remove('show');
            setTimeout(() => {
                modal.remove();
                resolve();
            }, 300);
        };

        confirmBtn.addEventListener('click', closeModal);

        // 点击遮罩层关闭
        const overlay = modal.querySelector('.modal-overlay');
        overlay.addEventListener('click', (e) => {
            if (e.target === overlay) {
                closeModal();
            }
        });

        // ESC键关闭
        const handleEscKey = (e) => {
            if (e.key === 'Escape') {
                closeModal();
                document.removeEventListener('keydown', handleEscKey);
            }
        };
        document.addEventListener('keydown', handleEscKey);
    });
}

// 自定义确认对话框组件
function showConfirmDialog(message, title = '确认') {
    return new Promise((resolve) => {
        // 移除已存在的模态框
        const existingModal = document.getElementById('custom-confirm-dialog');
        if (existingModal) {
            existingModal.remove();
        }

        // 创建模态框元素
        const modal = document.createElement('div');
        modal.id = 'custom-confirm-dialog';
        modal.className = 'custom-modal';

        // 设置模态框内容
        modal.innerHTML = `
            <div class="modal-overlay">
                <div class="modal-container">
                    <div class="modal-header">
                        <h3>${title}</h3>
                    </div>
                    <div class="modal-body">
                        <p>${message}</p>
                    </div>
                    <div class="modal-footer">
                        <button class="modal-cancel-btn">取消</button>
                        <button class="modal-confirm-btn">确定</button>
                    </div>
                </div>
            </div>
        `;

        // 添加到页面
        document.body.appendChild(modal);

        // 显示动画
        setTimeout(() => {
            modal.classList.add('show');
        }, 10);

        // 绑定确认按钮事件
        const confirmBtn = modal.querySelector('.modal-confirm-btn');
        const cancelBtn = modal.querySelector('.modal-cancel-btn');

        const closeWithResult = (result) => {
            modal.classList.remove('show');
            setTimeout(() => {
                modal.remove();
                resolve(result);
            }, 300);
        };

        confirmBtn.addEventListener('click', () => closeWithResult(true));
        cancelBtn.addEventListener('click', () => closeWithResult(false));

        // 点击遮罩层关闭（相当于取消）
        const overlay = modal.querySelector('.modal-overlay');
        overlay.addEventListener('click', (e) => {
            if (e.target === overlay) {
                closeWithResult(false);
            }
        });

        // ESC键关闭（相当于取消）
        const handleEscKey = (e) => {
            if (e.key === 'Escape') {
                closeWithResult(false);
                document.removeEventListener('keydown', handleEscKey);
            }
        };
        document.addEventListener('keydown', handleEscKey);
    });
}

// 初始化菜单功能
function initializeMenu() {
    // 获取所有菜单项
    const menuItems = document.querySelectorAll('.menu-item.has-children');

    // 为每个菜单项添加点击事件监听器
    menuItems.forEach(item => {
        const label = item.querySelector('.menu-label');
        const submenu = item.querySelector('.submenu');
        const checkbox = item.querySelector('.menu-checkbox');

        if (label && submenu) {
            label.addEventListener('click', function (e) {
                // 阻止事件冒泡
                e.stopPropagation();

                // 切换子菜单显示状态
                submenu.classList.toggle('open');
                item.classList.toggle('open');
            });
        }
    });
}

// 显示开发中功能提示
function showDevelopingFeature(featureName) {
    document.getElementById('page-title').textContent = featureName;
    document.getElementById('breadcrumb-text').textContent = featureName;

    const content = `
        <div style="display: flex; justify-content: center; align-items: center; width: 100%;">
            <div style="text-align: center; padding: 3rem; background: #f8f9fa; border-radius: 15px; box-shadow: 0 8px 16px rgba(0,0,0,0.1); max-width: 100%; width: 100%;">
                <div style="font-size: 4rem; margin-bottom: 1.5rem;">🚧</div>
                <h3 style="color: #1a5a94; margin-bottom: 1.5rem; font-size: 2rem;">功能正在开发中</h3>
                <p style="color: #666; margin-bottom: 2rem; font-size: 1.1rem; line-height: 1.6;">
                    "${featureName}" 功能目前正在紧张开发中，敬请期待！
                </p>
            </div>
        </div>
    `;

    document.getElementById('page-content').innerHTML = content;
}

function loadCatalogRelation() {
    // 设置页面标题和面包屑
    document.getElementById('page-title').textContent = '认领目录列表';
    document.getElementById('breadcrumb-text').textContent = '认领目录列表';

    // 使用新的后端渲染方式
    fetch('/fragments/catalog-relation')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.text();
        })
        .then(html => {
            // 检查返回内容是否为登录页面
            if (checkLoginPage(html)) {
                return;
            }
            document.getElementById('page-content').innerHTML = html;
            // 绑定事件监听器
            bindCatalogRelationEvents();
        })
        .catch(error => {
            if (error.message !== 'Session expired') {
                console.error('Error loading catalog relation fragment:', error);
                document.getElementById('page-content').innerHTML = '<p>加载失败: ' + error.message + '</p>';
            }
        });
}

// 加载目录数据
function loadMuluzhiliData(page) {
    const cataTitle = document.getElementById('search-cataTitle').value;
    const internalOrgName = document.getElementById('search-internalOrgName').value;

    let url = '/fragments/catalog-relation?page=' + page + '&limit=10';
    if (cataTitle) {
        url += '&cataTitle=' + encodeURIComponent(cataTitle);
    }
    if (internalOrgName) {
        url += '&internalOrgName=' + encodeURIComponent(internalOrgName);
    }

    fetch(url)
        .then(response => response.text())
        .then(html => {
            document.getElementById('page-content').innerHTML = html;
            // 重新绑定事件监听器
            bindCatalogRelationEvents();
        })
        .catch(error => {
            if (error.message !== 'Session expired') {
                console.error('Error loading muluzhili data:', error);
                document.getElementById('page-content').innerHTML = '<p>数据加载失败</p>';
            }
        });
}

// 绑定认领目录页面的事件监听器
function bindCatalogRelationEvents() {
    // 为按部门上报按钮添加事件监听器
    const uploadByDeptBtn = document.querySelector('.upload-by-dept-btn');
    if (uploadByDeptBtn) {
        uploadByDeptBtn.addEventListener('click', showUploadByDeptDialog);
    }

    // 为上报所有目录按钮添加事件监听器
    const uploadAllBtn = document.querySelector('.upload-all-btn');
    if (uploadAllBtn) {
        uploadAllBtn.addEventListener('click', uploadAllCatalogData);
    }

    // 为查询按钮添加事件监听器
    const searchBtn = document.querySelector('.search-btn');
    if (searchBtn) {
        searchBtn.addEventListener('click', function () { loadMuluzhiliData(1); });
    }

    // 为重置按钮添加事件监听器
    const resetBtn = document.querySelector('.reset-btn');
    if (resetBtn) {
        resetBtn.addEventListener('click', resetMuluzhiliSearch);
    }
}

// 重置搜索条件
function resetMuluzhiliSearch() {
    document.getElementById('search-cataTitle').value = '';
    document.getElementById('search-internalOrgName').value = '';
    loadMuluzhiliData(1);
}

// 跳转到指定页
function goToMuluzhiliPage(totalPages) {
    const pageInput = document.getElementById('muluzhili-page-input');
    const page = parseInt(pageInput.value);
    if (page && page >= 1 && page <= totalPages) {
        loadMuluzhiliData(page);
    } else {
        showNotification('请输入有效的页码 (1-' + totalPages + ')', 'warning');
    }
}

// 上报所有目录数据到目录治理数据库
function uploadAllCatalogData() {
    showConfirmDialog('确定要上报所有认领目录数据到目录治理数据库吗？')
        .then(result => {
            if (result) {
                // 显示加载提示
                const originalHtml = document.getElementById('page-content').innerHTML;
                document.getElementById('page-content').innerHTML = '<p style="text-align: center;">正在上报所有数据，请稍候...</p>';
                // 显示等待浮窗
                showLoadingModal();

                // 发送请求上报所有数据
                fetchWithAuth('/muluzhili/uploadAllCatalogData', {
                    method: 'POST'
                })
                    .then(data => {
                        // 隐藏等待浮窗
                        hideLoadingModal();
                        if (data && typeof data === 'object') {
                            if (data.code === 0) {
                                showModalDialog('数据上报成功！' + (data.msg ? data.msg : ''), '操作成功', 'success');
                            } else {
                                showModalDialog('数据上报失败：' + (data.msg ? data.msg : '未知错误'), '操作失败', 'error');
                            }
                        } else {
                            showModalDialog('数据上报成功！服务器没有返回详细信息', '操作成功', 'success');
                        }
                        // 恢复原始页面内容
                        document.getElementById('page-content').innerHTML = originalHtml;
                        // 重新加载数据
                        loadCatalogRelation();
                    })
                    .catch(error => {
                        // 隐藏等待浮窗
                        hideLoadingModal();
                        console.error('Error uploading all catalog data:', error);
                        showModalDialog('数据上报失败：' + error.message, '操作失败', 'error');
                        // 恢复原始页面内容
                        document.getElementById('page-content').innerHTML = originalHtml;
                        // 重新加载数据
                        loadCatalogRelation();
                    });
            }
            // 如果result为false，则什么也不做，相当于用户点击了取消
        });
}

// 显示按部门上报目录对话框
function showUploadByDeptDialog() {
    const modal = document.getElementById('uploadByDeptModal');
    if (modal) {
        modal.style.display = 'block';
    } else {
        console.error('找不到ID为uploadByDeptModal的元素');
        return;
    }

    // 添加表单提交事件监听器
    const form = document.getElementById('uploadByDeptForm');
    if (form) {
        // 先移除可能已存在的事件监听器，避免重复绑定
        const newForm = form.cloneNode(true);
        form.parentNode.replaceChild(newForm, form);
        newForm.addEventListener('submit', function (e) {
            e.preventDefault();
            uploadCatalogByDept();
        });
    }
}

// 关闭按部门上报目录对话框
function closeUploadByDeptModal() {
    const modal = document.getElementById('uploadByDeptModal');
    if (modal) {
        modal.style.display = 'none';
    }
}

// 按部门上报目录数据
function uploadCatalogByDept() {
    const deptSelect = document.getElementById('deptCode');
    const selectedOption = deptSelect.options[deptSelect.selectedIndex];
    const deptCode = selectedOption.value;
    const deptName = selectedOption.text;

    if (!deptCode) {
        showNotification('请选择部门', 'warning');
        return;
    }

    showConfirmDialog('确定要上报' + deptName + '的目录吗？')
        .then(result => {
            if (result) {
                // 显示加载提示
                const originalHtml = document.getElementById('page-content').innerHTML;
                document.getElementById('page-content').innerHTML = '<p style="text-align: center;">正在上报数据，请稍候...</p>';
                // 显示等待浮窗
                showLoadingModal();
                // 发送请求按部门上报数据
                fetchWithAuth('/muluzhili/uploadCatalogByDept?deptCode=' + encodeURIComponent(deptCode), {
                    method: 'POST'
                })
                    .then(data => {
                        // 隐藏等待浮窗
                        hideLoadingModal();
                        if (data && typeof data === 'object') {
                            if (data.code === 0) {
                                showModalDialog('数据上报成功！' + (data.msg ? data.msg : ''), '操作成功', 'success');
                            } else {
                                showModalDialog('数据上报失败：' + (data.msg ? data.msg : '未知错误'), '操作失败', 'error');
                            }
                        } else {
                            showModalDialog('数据上报成功！服务器没有返回详细信息', '操作成功', 'success');
                        }
                        // 关闭对话框
                        closeUploadByDeptModal();
                        // 恢复原始页面内容
                        document.getElementById('page-content').innerHTML = originalHtml;
                        // 重新加载数据
                        loadCatalogRelation();
                    })
                    .catch(error => {
                        console.error('Error uploading catalog data by department:', error);
                        showModalDialog('数据上报失败：' + error.message, '操作失败', 'error');
                        // 关闭对话框
                        closeUploadByDeptModal();
                        // 恢复原始页面内容
                        document.getElementById('page-content').innerHTML = originalHtml;
                        // 重新加载数据
                        loadCatalogRelation();
                    });
            }
        });
}

// 显示等待浮窗
function showLoadingModal() {
    // 检查是否已存在loading modal，如果不存在则创建
    let modal = document.getElementById('uploadLoadingModal');
    if (!modal) {
        modal = document.createElement('div');
        modal.id = 'uploadLoadingModal';
        modal.className = 'loading-modal';
        modal.style.display = 'none';
        modal.innerHTML = `
            <div class="loading-content">
                <div class="loading-spinner"></div>
                <p>数据正在上传中，请不要刷新页面...</p>
            </div>
        `;
        document.body.appendChild(modal);

        const style = document.createElement('style');
        style.textContent = `
            .loading-modal {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.5);
                z-index: 10000;
                display: flex;
                justify-content: center;
                align-items: center;
            }
            
            .loading-content {
                background-color: white;
                padding: 30px 50px;
                border-radius: 8px;
                text-align: center;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            }
            
            .loading-spinner {
                border: 4px solid #f3f3f3;
                border-top: 4px solid #1a5a94;
                border-radius: 50%;
                width: 40px;
                height: 40px;
                animation: spin 1s linear infinite;
                margin: 0 auto 20px;
            }
            
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        `;
        document.head.appendChild(style);
    }
    modal.style.display = 'flex';
}

// 隐藏等待浮窗
function hideLoadingModal() {
    const modal = document.getElementById('uploadLoadingModal');
    if (modal) {
        modal.style.display = 'none';
    }
}
// 加载上报目录列表页面
function loadUpDataCatalog(page = 1) {
    document.getElementById('page-title').textContent = '上报目录列表';
    document.getElementById('breadcrumb-text').textContent = '上报目录列表';

    // 构造URL，包含页码参数
    const url = `/fragments/up-data-catalog?page=${page}&limit=10`;

    fetch(url)
        .then(response => response.text())
        .then(html => {
            // 检查返回内容是否为登录页面
            if (checkLoginPage(html)) {
                return;
            }
            document.getElementById('page-content').innerHTML = html;

            // 添加事件监听器
            const form = document.getElementById('upDataCatalogSearchForm');
            if (form) {
                form.addEventListener('submit', function (e) {
                    e.preventDefault();
                    submitUpDataCatalogSearch();
                });
            }

            // 绑定分页链接的事件处理
            bindPaginationEvents();
        })
        .catch(error => {
            if (error.message !== 'Session expired') {
                console.error('Error loading updatacatalog fragment:', error);
                document.getElementById('page-content').innerHTML = '<p>加载失败</p>';
            }
        });
}

// 绑定分页链接事件
function bindPaginationEvents() {
    // 处理分页链接
    const paginationLinks = document.querySelectorAll('#updatacatalog-pagination a.pagination-btn');
    paginationLinks.forEach(link => {
        link.addEventListener('click', function (e) {
            e.preventDefault();
            const url = this.getAttribute('href');
            if (url) {
                fetch(url)
                    .then(response => response.text())
                    .then(html => {
                        document.getElementById('page-content').innerHTML = html;
                        document.getElementById('page-title').textContent = '上报目录列表';
                        document.getElementById('breadcrumb-text').textContent = '上报目录列表';

                        // 重新绑定事件
                        const form = document.getElementById('upDataCatalogSearchForm');
                        if (form) {
                            form.addEventListener('submit', function (e) {
                                e.preventDefault();
                                submitUpDataCatalogSearch();
                            });
                        }

                        bindPaginationEvents();
                    })
                    .catch(error => {
                        console.error('Error loading page:', error);
                    });
            }
        });
    });

    // 处理跳转到指定页的功能
    const goToPageButton = document.querySelector('.pagination-input button');
    if (goToPageButton) {
        // 移除原有的onclick属性，重新绑定事件
        goToPageButton.addEventListener('click', function (e) {
            e.preventDefault();
            const pageInput = document.getElementById('page-input');
            const page = parseInt(pageInput.value);
            if (page && !isNaN(page)) {
                goToPageByNumber(page);
            }
        });
    }
}

// 根据页码跳转
function goToPageByNumber(page) {
    // 获取当前的搜索条件
    const cataTitle = document.getElementById('search-cataTitle').value;
    const importedByOrgName = document.getElementById('search-internalOrgName').value;

    let url = `/fragments/up-data-catalog?page=${page}&limit=10`;
    if (cataTitle) {
        url += `&cataTitle=${encodeURIComponent(cataTitle)}`;
    }
    if (importedByOrgName) {
        url += `&importedByOrgName=${encodeURIComponent(importedByOrgName)}`;
    }

    fetch(url)
        .then(response => response.text())
        .then(html => {
            document.getElementById('page-content').innerHTML = html;
            document.getElementById('page-title').textContent = '上报目录列表';
            document.getElementById('breadcrumb-text').textContent = '上报目录列表';

            // 重新绑定事件
            const form = document.getElementById('upDataCatalogSearchForm');
            if (form) {
                form.addEventListener('submit', function (e) {
                    e.preventDefault();
                    submitUpDataCatalogSearch();
                });
            }

            bindPaginationEvents();
        })
        .catch(error => {
            console.error('Error loading page:', error);
        });
}

// 提交搜索表单
function submitUpDataCatalogSearch() {
    const form = document.getElementById('upDataCatalogSearchForm');
    if (!form) return;

    const formData = new FormData(form);
    const params = new URLSearchParams(formData).toString();
    const url = `/fragments/up-data-catalog?${params}`;

    fetch(url)
        .then(response => response.text())
        .then(html => {
            document.getElementById('page-content').innerHTML = html;
            document.getElementById('page-title').textContent = '上报目录列表';
            document.getElementById('breadcrumb-text').textContent = '上报目录列表';

            // 重新绑定事件监听器
            const newForm = document.getElementById('upDataCatalogSearchForm');
            if (newForm) {
                newForm.addEventListener('submit', function (e) {
                    e.preventDefault();
                    submitUpDataCatalogSearch();
                });
            }

            bindPaginationEvents();
        })
        .catch(error => {
            console.error('Error searching updatacatalog:', error);
            document.getElementById('page-content').innerHTML = '<p>搜索失败</p>';
        });
}

// 重置上报目录搜索条件
function resetUpDataCatalogSearch() {
    document.getElementById('search-cataTitle').value = '';
    document.getElementById('search-internalOrgName').value = '';
    // 重置后重新加载第一页
    loadUpDataCatalog(1);
}

// 通过ID重新上报目录
function reuploadCatalogById(id) {
    // 通过AJAX获取完整对象数据
    fetch(`/updatacatalog/data-item?id=${id}`)
        .then(response => response.json())
        .then(item => {
            reuploadCatalog(item);
        })
        .catch(error => {
            console.error('Error fetching catalog item:', error);
        });
}

function reuploadCatalog(item) {
    // 保存当前页码，用于返回时使用
    const currentPage = document.querySelector('#updatacatalog-pagination .active')?.textContent || 1;

    fetch(`/updatacatalog/up-data-catalog-detail?id=${item.id}`)
        .then(response => response.text())
        .then(html => {
            document.getElementById('page-content').innerHTML = html;
            document.getElementById('page-title').textContent = '目录详情';
            document.getElementById('breadcrumb-text').textContent = '目录详情';

            // 使用事件委托绑定返回按钮事件
            document.getElementById('page-content').addEventListener('click', function (event) {
                if (event.target.id === 'backButton' || event.target.closest('#backButton')) {
                    event.preventDefault();
                    backToUpDataCatalog(currentPage);
                }
            });

            // 绑定重新上报按钮事件
            const reuploadButton = document.getElementById('reuploadButton');
            if (reuploadButton) {
                reuploadButton.onclick = function () {
                    confirmReupload(item.id);
                };
            }

            const updateCatalogButton = document.getElementById('updateCatalogButton');
            if (updateCatalogButton) {
                updateCatalogButton.onclick = function () {
                    updateCatalog();
                };
            }
        })
        .catch(error => {
            console.error('Error loading catalog detail:', error);
            document.getElementById('page-content').innerHTML = '<p>加载详情失败: ' + error.message + '</p>';
        });
}

// 返回上报目录列表
function backToUpDataCatalog(page) {
    // 重新加载整个页面主体内容，并传递需要返回的页码
    loadUpDataCatalog(page);

    // 稍微延迟一下设置标题，确保DOM已更新
    setTimeout(() => {
        document.getElementById('page-title').textContent = '上报目录列表';
        document.getElementById('breadcrumb-text').textContent = '上报目录列表';
    }, 0);
}

// 重新上报
function confirmReupload(id) {
    showCustomConfirm(
        '确定要重新上报该目录吗？<br/><span style="color: red;">通常在省级抽取目录之后发现错误，修改目录错误信息后重新上报，会生成一个新的批次号。）</span>', function () {
            // 获取表单数据
            const form = document.getElementById('catalogEditForm');
            const formData = new FormData(form);

            showLoadingModal();
            // 发送重新上报请求
            fetch('/updatacatalog/reupload', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(result => {
                    hideLoadingModal();
                    if (result.code === 0) {
                        showModalDialog(('重新上报成功'));
                    } else {
                        showModalDialog(('重新上报失败', result.msg));
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showModalDialog(('上报失败', error));
                });
        }
    );
}

function updateCatalog() {
    showCustomConfirm(
        '要更新目录信息吗？<br/><span style="color: red;">（通常在省级抽取目录信息之前，发现该目录信息有错误时进行修改，原有批次号信息不变。）</span>',
        function () {
            const form = document.getElementById('catalogEditForm');
            const formData = new FormData(form);

            showLoadingModal();
            // 发送更新请求
            fetch('/updatacatalog/update', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(result => {
                    hideLoadingModal();
                    if (result.code === 0) {
                        showModalDialog(('更新成功', '更新目录成功'));
                    } else {
                        showModalDialog(('更新失败', result.msg));
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showModalDialog(('更新失败', error));
                });
        }

    );
}

// 自定义确认对话框函数
function showCustomConfirm(message, onConfirm) {
    // 创建遮罩层
    const overlay = document.createElement('div');
    overlay.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 9999;
    `;

    // 创建对话框
    const dialog = document.createElement('div');
    dialog.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        z-index: 10000;
        max-width: 400px;
        text-align: center;
    `;

    // 创建消息内容
    const messageElement = document.createElement('div');
    messageElement.innerHTML = message;
    messageElement.style.cssText = `
        margin-bottom: 20px;
        line-height: 1.5;
    `;

    // 创建按钮容器
    const buttonContainer = document.createElement('div');
    buttonContainer.style.cssText = `
        display: flex;
        justify-content: center;
        gap: 10px;
    `;

    // 创建确认按钮
    const confirmButton = document.createElement('button');
    confirmButton.textContent = '确认';
    confirmButton.style.cssText = `
        padding: 8px 16px;
        background-color: #1a5a94;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    `;
    confirmButton.addEventListener('click', function () {
        document.body.removeChild(overlay);
        if (onConfirm) onConfirm();
    });

    // 创建取消按钮
    const cancelButton = document.createElement('button');
    cancelButton.textContent = '取消';
    cancelButton.style.cssText = `
        padding: 8px 16px;
        background-color: #f8f9fa;
        color: #333;
        border: 1px solid #ccc;
        border-radius: 4px;
        cursor: pointer;
    `;
    cancelButton.addEventListener('click', function () {
        document.body.removeChild(overlay);
    });

    // 组装对话框
    buttonContainer.appendChild(confirmButton);
    buttonContainer.appendChild(cancelButton);

    dialog.appendChild(messageElement);
    dialog.appendChild(buttonContainer);

    overlay.appendChild(dialog);
    document.body.appendChild(overlay);
}

// 加载修改密码页面
function loadChangePassword() {
    // 更新页面标题和面包屑
    document.getElementById('page-title').textContent = '修改密码';
    document.getElementById('breadcrumb-text').textContent = '修改密码';

    // 使用 AJAX 加载修改密码片段
    fetch('/fragments/change-password')
        .then(response => response.text())
        .then(html => {
            document.getElementById('page-content').innerHTML = html;
            // 绑定密码验证事件
            bindChangePasswordEvents();
        })
        .catch(error => {
            console.error('Error loading change password fragment:', error);
            document.getElementById('page-content').innerHTML = '<p>加载失败，请刷新页面重试。</p>';
        });
}

// 绑定修改密码页面的事件
function bindChangePasswordEvents() {
    const newPasswordInput = document.getElementById('newPassword');
    const passwordHint = document.getElementById('passwordHint');
    const changePasswordForm = document.getElementById('changePasswordForm');
    
    if (newPasswordInput && passwordHint) {
        newPasswordInput.addEventListener('input', function() {
            const password = this.value;
            
            if (password.length > 0 && password.length < 6) {
                passwordHint.style.display = 'block';
            } else {
                passwordHint.style.display = 'none';
            }
        });
    }
    
    if (changePasswordForm) {
        changePasswordForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const oldPassword = document.getElementById('oldPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmNewPassword').value;
            
            // 前端验证
            if (newPassword.length < 6) {
                alert('密码长度不能少于6位');
                return;
            }
            
            if (newPassword !== confirmPassword) {
                alert('新密码与确认密码不匹配');
                return;
            }
            
            // 创建FormData对象
            const formData = new FormData();
            formData.append('oldPassword', oldPassword);
            formData.append('newPassword', newPassword);
            formData.append('confirmNewPassword', confirmPassword);
            
            // 发送AJAX请求
            fetch('/change-password', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 密码修改成功，显示成功消息
                    showNotification(data.message, 'success');
                    // 3秒后跳转到登录页面
                    setTimeout(() => {
                        window.location.href = '/login?changed=true';
                    }, 3000);
                } else {
                    // 显示错误消息
                    showNotification(data.error, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('发生未知错误，请重试', 'error');
            });
        });
    }
}